<template>
  <div class="page-container">
    <div class="in-container container">
      <!-- <AppSearchForm @submit="search" @reset="reset">
        <el-form-item>
          <el-input v-model="query.title" clearable> </el-input>
        </el-form-item>
      </AppSearchForm> -->
      <div class="btn-box">
        <el-button type="default" icon="RefreshRight" @click="getTableData">
        </el-button>
        <el-button type="primary" @click="openNew">新增</el-button>
      </div>

      <el-table
        v-loading="state.tableData.option.loading"
        border
        row-key="id"
        ref="tableRef"
        class="table"
        header-row-class-name="tableHeader"
        :data="state.tableData.data"
      >
        <el-table-column prop="name" label="名称" />

        <el-table-column prop="sort" label="排序">
          <template #default="scope">
            {{ scope.row.sort }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建日期">
          <template #default="scope">
            {{ parseTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="updateCompany(scope.row)" type="primary"
              >编辑</el-button
            >
            <el-button
              @click="editUserList(scope.row, scope.$index)"
              type="primary"
              >查看人员</el-button
            >
            <el-button
              @click="eidtUserBank(scope.row, scope.$index)"
              type="primary"
              >开票信息</el-button
            >
            <el-popconfirm
              title="确定删除本条数据(包括下级)吗？"
              @confirm="deleteCompany(scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-pagination
        small
        background
        class="page-component"
        layout="total, sizes, prev, pager, next"
        :page-sizes="[10, 20, 50]"
        :total="tableData.option.total"
        v-model:current-page="tableData.option.page"
        v-model:page-size="tableData.option.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      /> -->
      <!-- 开票信息页面 -->
      <el-dialog
        width="800px"
        v-model="state.userBankDialog.show"
        :title="state.userBankDialog.title"
        :data="state.formData"
        @close="bankcancel"
      >
        <AppSearchForm @submit="getBankList" @reset="resetBank">
          <el-form-item>
            <el-input
              v-model="state.query.title"
              clearable
              placeholder="请输入关键字"
            ></el-input>
          </el-form-item>
        </AppSearchForm>

        <div class="btn-box">
          <el-button type="primary" @click="addNew">新增</el-button>
          <el-button type="danger" @click="deleteBank"> 删除 </el-button>
        </div>

        <el-table
          max-height="450"
          :data="state.userBankDialog.tabledata" 
          stripe 
          border
          :cell-class-name="tableCellClassName"
          v-loading="state.userBankDialog.loading"
          @cell-click="cellClick"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column prop="currency" label="币种">
            <template #default="scope">
              <div v-if="scope.row.index === state.rowIndex">
                <selectDown
                  v-model:modelData="scope.row.currency"
                  placeholder="请输入后搜索"
                  urlType="currency"
                >
                </selectDown>
              </div>
              <span v-else>
                {{ scope.row.currency }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="accountName" label="户名">
            <template #default="scope">
              <div v-if="scope.row.index === state.rowIndex">
                <el-input v-model="scope.row.accountName" size="small"> </el-input>
              </div>
              <span v-else>
                {{ scope.row.accountName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="bankAccount" label="银行账号">
            <template #default="scope">
              <div v-if="scope.row.index === state.rowIndex">
                <el-input v-model="scope.row.bankAccount" size="small"> </el-input>
              </div>
              <span v-else>
                {{ scope.row.bankAccount }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="bankName" label="开户银行">
            <template #default="scope">
              <div v-if="scope.row.index === state.rowIndex">
                <el-input v-model="scope.row.bankName" size="small"> </el-input>
              </div>
              <span v-else>
                {{ scope.row.bankName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="memo" label="备注">
            <template #default="scope">
              <div v-if="scope.row.index === state.rowIndex">
                <el-input v-model="scope.row.memo" size="small"> </el-input>
              </div>
              <span v-else>
                {{ scope.row.memo }}
              </span>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="state.userBankDialog.show = false" link>取消</el-button>
            <el-button
              type="primary"
              @click="banksubmit"
              :loading="state.userBankDialog.btnLoading"
            >
              保存
            </el-button>
          </span>
        </template>
      </el-dialog>

      <CompanyFormDialog
        ref="dialog"
        :companyData="state.companyData"
        v-model:model-data="state.formData"
        v-model:dialog-data="state.dialogData"
        @submit="validSubmit"
        @cancel="cancel"
      >
      </CompanyFormDialog>
      <UserFormDialog
        :currentName="state.currentName"
        :companyId="state.CompanyId"
        v-model:userList="state.userList"
        v-model:dialog="state.userListDialog"
        @toChangeUserList="saveToUserList"
      >
        ></UserFormDialog
      >
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, reactive, nextTick } from "vue";
import AppSearchForm from "@/components/AppSearchForm.vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import CompanyFormDialog from "./components/companyFormDialog.vue";
import UserFormDialog from "./components/userFormDialog.vue";
import dayjs from "dayjs";
import request from "@/public/request";
import { ElMessageBox, ElMessage } from "element-plus";
import selectDown from "@/views/internal/enterprise/components/selectDown.vue";

const state = reactive({
  query: {
    title: "",
  },
  tableData: {
    data: [],
    option: useTableOption(),
  },
  dialogData: {
    show: false,
    title: "",
    btnLoading: false,
  },
  formData: {
    id: 0,
    //组织名称
    name: "",
    // 公司英文名
    nameEn: "",
    // 全称
    fullName: "",
    // 英文全称
    fullNameEn: "",
    // 排序
    sort: 0,
    //0 | null |"" 顶层
    parentId: "",
    // 地址
    address: "",
    // 公司英文地址
    addressEn: "",
    // 统一社会信用代码 | 营业执照代码
    unifiedSocialCreditCode: "",
    // logo地址
    logoUrl: "",
    // 公司简介
    profile: "",
    // 公司邮编
    zipCode: "",
    // 公司传真
    fax: "",
    // 负责人
    director: "",
    // 手机
    telphone: "",
    // 邮箱
    email: "",
    // 备注
    description: "",
    // 法人 | 负责人 暂且为空
    legalPerson: "",

    //开票信息
    companyId: "",
    currency: "",
    accountName: "",
    bankAccount: "",
    bankName: "",
    memo: "",
    isDeleted: "",
    creatBy: "",
    creatTime: "",
    updateBy: "",
    updateTime: "",
  },
  extendsTreeNode: new Map(),
  companyData: [],
  updateId: 0,
  //查看用户弹窗数据
  userListDialog: {
    show: false,
    btnLoading: false,
  },
  //查看用户银行信息
  userBankDialog: {
    show: false,
    btnLoading: false,
    loading: false,
    title: "",
    tabledata: []
  },
  //编辑角色授权用户时 保存该角色的授权用户数据
  userList: [],
  //编辑角色授权用户时 保存该角色的授权用户数据下标
  userListIndex: 0,
  //编辑角色授权用户时 保存该角色id
  CompanyId: "",
  currentName: "",
  rowIndex: -1, //行索引
  columnIndex: -1, //列索引
  selectData: [],
  itemKey: 0
});

const parseTime = (date) => {
  if (date) {
    return dayjs(date).format("YYYY-MM-DD");
  }
  return date;
};

const tableCellClassName = ({ row, column, rowIndex, columnIndex }) => {
  column.index = columnIndex;
  row.index = rowIndex;
};
const cellClick = (row, column, cell, event) => {
  state.rowIndex = row.index;
  state.columnIndex = column.index;
};
const handleSelectionChange = (selection) => {
  state.selectData = selection;
};

// 获取公司信息
const getTableData = async () => {
  state.tableData.option.loading = true;
  request
    .get("/api/company/buildTree", {
      KeyWords: state.query.title,
    })
    .then((res) => {
      state.tableData.data = res;
    })
    .finally(() => (state.tableData.option.loading = false));
};
// 信息更新
const updateCompany = (row) => {
  state.dialogData.title = "修改公司";
  let tableCopy = JSON.parse(JSON.stringify(state.tableData.data));
  state.updateId = row.id;
  companyFilter(tableCopy);
  state.companyData = tableCopy;
  state.dialogData.show = true;
  if (row.parentId == "0") {
    row.parentId = "";
  }
  nextTick(() => {
    state.formData = JSON.parse(JSON.stringify(row));
  });
};
// 员工列表弹窗
const editUserList = (row, index) => {
  state.currentName = row.name;
  state.userListIndex = index;
  state.CompanyId = row.id;
  state.userList = row.users;
  state.userListDialog.show = true;
};
// 开票信息弹窗
const eidtUserBank = (row, index) => {
  state.userBankDialog.title = "开票信息";
  state.userBankDialog.show = true;
  state.memo = row.memo;
  state.accountName = row.accountName;
  state.CompanyId = row.id;
  state.bankAccount = row.bankAccount;
  state.currency = row.currency;
  getBankList();
};
// 获取公司开票信息列表
const getBankList = async () => {
  let res = await request.get('/api/companybank/query',{
    KeyWords: state.query.title,
    CompanyId: state.CompanyId,
    PageIndex: 1,
    PageSize: 999
  });
  state.userBankDialog.tabledata = res.content;
}
//重置搜索条件
const resetBank = () => {
  state.query.title = "";
  getBankList();
};
// 新增开票信息点击
const addNew = () => {
  state.userBankDialog.tabledata.push({
    id: 0,
    companyId: state.CompanyId,
    currency: "",
    accountName: "",
    bankAccount: "",
    bankName: "",
    memo: "",
  });
  state.userBankDialog.tabledata = state.userBankDialog.tabledata.slice(0);
}
// 删除开票银行
const deleteBank = () => {
  let newArray = [];
  state.userBankDialog.tabledata.forEach((t) => {
    if (!state.selectData.find((item) => t == item)) {
      newArray.push(t);
    }
  });
  state.userBankDialog.tabledata = newArray;
  state.rowIndex = -1; //行索引
  state.columnIndex = -1; //列索引
}
// 开票信息校验
const validData = () => {
  for (let i of state.userBankDialog.tabledata) {
    for (let j of Object.keys(i)) {
      if (
        j == "currency" ||
        j == "accountName" ||
        j == "bankAccount" ||
        j == "bankName" ||
        j == "companyId"
      ) {
        if (!i[j]) {
          return false;
        }
      } else {
        continue;
      }
    }
  }
  return true;
};
// 开票信息提交保存
const banksubmit = async () => {
  if (validData()) {
    let newFormData = JSON.parse(JSON.stringify(state.userBankDialog.tabledata));
    newFormData.forEach((t) => {
      delete t.index;
    });
    // 判断列表数据是否存在币种，收款户名，银行账号，开户账户是否有完全相同的数据
    let hasSameObj = false;
    for (let i = 0; i < newFormData.length; i++) {
      hasSameObj = false;
      let checkObj = newFormData[i];
      for (let j = i + 1; j < newFormData.length; j++) {
        let sigleObj = newFormData[j];
        if (
          checkObj.currency == sigleObj.currency &&
          checkObj.accountName == sigleObj.accountName &&
          checkObj.bankAccount == sigleObj.bankAccount &&
          checkObj.bankName == sigleObj.bankName
        ) {
          hasSameObj = true;
          break;
        }
      }
      if (hasSameObj) {
        break;
      }
    }
    if (hasSameObj) {
      ElMessage.warning("列表数据存在两条相同的数据");
      return;
    }
    state.userBankDialog.btnLoading = true;
    request.post('/api/companybank/save',{
      companyId: state.CompanyId,
      createUpdateCompanyBankDtos: newFormData
    }).then((res) => {
        if (res.status) {
          state.userBankDialog.show = false;
          ElMessage.success(res.message);
        } else {
          ElMessage.error(res.message);
        }
      })
      .finally(() => (state.userBankDialog.btnLoading = false));
  } else {
    ElMessage.warning("数据中存在币种、收款户名、银行账号、开户账号为空");
  }
}
const bankcancel = () => {
  state.userBankDialog.show = false;
  state.userBankDialog.tabledata = [];
  state.query.title = '';
  state.rowIndex = -1; //行索引
  state.columnIndex = -1; //列索引
}
// 关闭开票信息弹窗
const cancelUserBankDialog = () => {
  state.userBankDialog.show = false;
};
// 删除公司
const deleteCompany = (row) => {
  request
    .post("/api/company/delete", {
      idArray: [row.id],
    })
    .then((res) => {
      if (res.status) {
        getTableData();
        ElMessage.success(res.message);
      } else {
        ElMessage.error(res.message);
      }
    });
};
// 提交校验
const validSubmit = () => {
  if (
    !state.formData.id &&
    !state.formData.parentId &&
    state.tableData.data.length > 0
  ) {
    ElMessage.warning("请选择所属公司");
  } else {
    submit();
  }
};
const dialog = ref();
// 提交修改
const submit = () => {
  let url = "";
  if (state.formData.id) {
    url = "/api/company/edit";
  } else {
    url = "/api/company/create";
  }
  dialog.value.$refs.form.validate((valid) => {
    if (valid) {
      state.dialogData.btnLoading = true;
      request
        .post(url, state.formData)
        .then((res) => {
          if (res.status) {
            getTableData();
            ElMessage.success(res.message);
            state.dialogData.show = false;
          } else {
            ElMessage.error(res.message);
          }
        })
        .finally(() => (state.dialogData.btnLoading = false));
    }
  });
};
// 关闭弹窗
const cancel = () => {
  state.dialogData.show = false;
};
// 打开新增公司弹窗
const openNew = () => {
  state.dialogData.show = true;
  state.dialogData.title = "新增公司";
  state.companyData = state.tableData.data;
};
// 筛选公司
const companyFilter = (data) => {
  for (let i = 0; i < data.length; i++) {
    if (data[i].id == state.updateId) {
      data.splice(i, 1);
    } else {
      if (data[i].children.length > 0) {
        companyFilter(data[i].children);
      }
    }
  }
};
// 员工搜索
const search = () => {
  request
    .get("/api/user/query", {
      KeyWords: state.query.title,
    })
    .then((res) => {
      state.formData = res;
    });
};
// 员工搜索重置
const resent = () => {
  request.get("api/user/query").then((res) => {
    state.formData = res;
  });
};
watch(state.dialogData.show, (newVal, oldVal) => {
  if (!newVal) {
    nextTick(() => {
      state.formData.id = "";
      dialog.value.$refs["form"].resetFields();
    });
  }
});

onMounted(() => {
  getTableData();
});
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;

  .btn-box {
    margin-bottom: 8px;
  }

  .table {
    flex: 1;

    :deep(.tableHeader) th {
      background-color: #f7f8fa !important;
    }
  }

  .page-component {
    justify-content: flex-end;
    margin-top: 10px;
  }
}

// .el-dialog {
//   font-size: 12px;

//   .trun {
//     display: flex;
//     align-items: center;
//     font-size: 12px;
//     margin-bottom: 8px;
//     .trun-header {
//       width: 120px;
//       line-height: 32px;
//       height: 32px;
//       padding-right: 12px;
//       text-align: right;
//     }
//     :deep(.el-radio) {
//       font-size: 12px;
//     }
//   }
// }
</style>
